package com.minminaya.mediaservice.Activity;
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.minminaya.mediaservice.R;
import com.minminaya.mediaservice.Service.MediaService;
import java.text.SimpleDateFormat;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
    @Bind(R.id.seekbar)
    SeekBar seekBar;
    @Bind(R.id.text1)
    TextView   textView;
    private Handler handler = new Handler();
    private MediaService.BinderExd binder;
    private SimpleDateFormat time = new SimpleDateFormat("m:ss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //判断权限够不够，不够就给
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {//够了就设置路径等，准备播放
            bindService( new Intent(this, MediaService.class), connection, BIND_AUTO_CREATE);
        }
    }
    //获取到权限回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull  String[]permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    bindService( new Intent(this, MediaService.class), connection, BIND_AUTO_CREATE);
                } else {
                    Toast.makeText(this, "权限不够获取不到音乐，程序将退出", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MediaService.BinderExd)service;
            seekBar.setMax(binder.getProgress());
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser) {
                    //这里很重要，如果不判断是否来自用户操作进度条，会不断执行下面语句块里面的逻辑，然后就会卡顿卡顿
                    if(fromUser){
                        binder.seekToPositon(seekBar.getProgress());
                    }
                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            handler.post(runnable);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    @OnClick({R.id.play,R.id.pause,R.id.next, R.id.precious,R.id.gcc})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                binder.play();
                break;
            case R.id.pause:
                binder.pause();
                break;
            case R.id.next:
                binder.next();
                break;
            case R.id.precious:
                binder.precious();
                break;
            case R.id.gcc:
                binder.gcc();
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //我们的handler发送是定时1000s发送的，如果不关闭，MediaPlayer release掉了还在获取getCurrentPosition就会爆IllegalStateException错误
        handler.removeCallbacks(runnable);
        binder.close();
        unbindService(connection);
    }
    /**
     * 更新ui的runnable
     */
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            seekBar.setProgress(binder.getPlayPosition());
            textView.setText(time.format(binder.getPlayPosition()) + "s");
            handler.postDelayed(runnable, 1000);
        }
    };

}
